<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>参数管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="paramscard">
      <el-alert class="paramsalert"
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false">
      </el-alert>

      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectcateKeys"
            :options="catelist"
            :props="cateProps"
            @change="catehandleChange">
          </el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isbtnDisable" @click="showAddDialog">添加参数</el-button>

          <el-table :data="manyTableData" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleTagClose(index,scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" class="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" size="mini" class="el-icon-delete" @click="deleteparams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isbtnDisable"  @click="showAddDialog">添加属性</el-button>

          <el-table :data="onlyTableData" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleTagClose(index,scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" class="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" size="mini" class="el-icon-delete" @click="deleteparams(scope.row.attr_id)">删除</el-button>
              </template>            
            </el-table-column>
          </el-table>

        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="adddialogVisible"
      width="50%"
      @close="addDialogClosed">
      <el-form :model="addruleForm" :rules="addruleFormRules" ref="addruleFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addruleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adddialogcomfirm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="'编辑'+titleText"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editDialogClosed">
      <el-form :model="editruleForm" :rules="editruleFormRules" ref="editruleFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editruleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editdialogcomfirm">确 定</el-button>        
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Goodsparams",
  data(){
    return{
      // 级联选择器的数据
      catelist:[],
      selectcateKeys: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },

      // tabs导航栏部分数据
      activeName: 'many',
      onlyTableData: [],
      manyTableData: [],

      // 添加参数和属性的对话框数据
      adddialogVisible: false,
      addruleForm: {
        attr_name: ''
      },
      addruleFormRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ]
      },

      // 编辑参数和属性的对话框数据
      editdialogVisible: false,
      editruleForm: {
        attr_name: ''
      },
      editruleFormRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ]
      },

      // 删除参数
      deleteparams(id){
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(res => {
            this.$http.delete(`categories/${this.cateid}/attributes/${id}`).then(res=>{
              if(res.status !== 200) return this.$message.error("删除失败");
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.getattrlist();
              // console.log(res);
            }).catch(err=>console.log(err));         
          })
          .catch((err) => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
      },

      
    }
  },
  created() {
    this.getcatelist();
  },
  methods: {
    async getcatelist(){
      const {data: res} = await this.$http.get("/categories");
      if(res.meta.status !== 200) return this.$message.error("获取商品列表失败");
      this.catelist = res.data;
      // console.log(res.data);
    },

    catehandleChange(){
      // console.log(this.selectcateKeys);
      this.getattrlist();
      if(this.selectcateKeys !== 3){
        this.manyTableData = [];
        this.onlyTableData = [];
      }
    },

    // tabs标签栏部分方法
    handleTabClick(){
      // console.log(this.activeName);
      this.getattrlist();
    },

    // 获取属性数据
    async getattrlist(){
      if(this.cateid === null) return;
      const {data: res} = await this.$http.get(`/categories/${this.cateid}/attributes`,{
        params:{
          sel: this.activeName
        }
      });
      
      res.data.forEach(item=>{
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      // console.log(res.data);
      if(this.activeName === "many"){
        this.manyTableData = res.data;
      }else{
        this.onlyTableData = res.data;
      }
    },

    // 添加参数和属性的点击事件
    showAddDialog(){
      this.adddialogVisible = true;
    },

    addDialogClosed(){
      this.$refs.addruleFormRef.resetFields();
    },
    adddialogcomfirm(){
      this.$refs.addruleFormRef.validate(async valid=>{
        if(!valid) return;
        const {data: res} = await this.$http.post(`categories/${this.cateid}/attributes`,{
          attr_name: this.addruleForm.attr_name,
          attr_sel: this.activeName
        })
        if(res.meta.status !== 201) return this.$message.error("添加失败")
        this.$message.success("添加成功")
        this.adddialogVisible = false;
        this.getattrlist();
        this.$refs.addruleFormRef.resetFields();
      })
      
    },

    // 编辑参数和属性的点击事件
    async showEditDialog(id){
      const {data: res} = await this.$http.get(`categories/${this.cateid}/attributes/${id}`,{
        attr_sel: this.activeName
      });
      this.editruleForm = res.data;
      this.editdialogVisible = true;

    },
    editDialogClosed(){
      this.$refs.editruleFormRef.resetFields();
    },
    editdialogcomfirm(){
      this.$refs.editruleFormRef.validate(async valid=>{
        if(!valid) return;
        const {data : res} = await this.$http.put(`categories/${this.cateid}/attributes/${this.editruleForm.attr_id}`,{
          attr_name: this.editruleForm.attr_name,
          attr_sel: this.activeName
        })
        if(res.meta.status !== 200) return this.$message.error("编辑提交失败")
        this.$message.success("编辑提交成功")
        this.getattrlist();
        this.$refs.editruleFormRef.resetFields();
        this.editdialogVisible = false;
      })
    },

    // *******************
    async handleInputConfirm(row){
      if(row.inputValue.trim().length === 0){
        row.inputValue = "",
        row.inputVisible = false;
        return;
      };
      row.attr_vals.push(row.inputValue.trim());
      

      const {data: res} = await this.$http.put(`categories/${this.cateid}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(","),
      })

      row.inputValue = "";
      row.inputVisible = false;

    },

    async handleTagClose(index,row){
      row.attr_vals.splice(index,1);
      const {data: res} = await this.$http.put(`categories/${this.cateid}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(","),
      })
    },

    showInput(row){
      row.inputVisible = true;
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
      });
    }

  },
  computed: {
    isbtnDisable(){
      if(this.selectcateKeys.length !== 3){
        return true;
      }else{
        return false;
      }
    },
    cateid(){
      if(this.selectcateKeys.length === 3){
        return this.selectcateKeys[2];
      }
      return null;
    },
    titleText(){
      if(this.activeName === 'many'){
        return "动态参数"
      }
      return "静态属性"
    }

  }
}
</script>

<style scpoed>
  .el-tag{
    margin: 7px;
  }

  .paramscard{
    margin-top: 30px;
  }

  .paramsalert{
    margin-bottom: 20px;
  }

  .el-tabs{
    margin-top: 20px;
  }

  .el-table{
    margin-top: 20px;
  }

  .el-cascader{
    margin-top: 15px;
  }

  .input-new-tag{
    width: 150px;
  }
</style>